package org.example.taobao.demo.good.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.taobao.demo.good.repository.entity.GoodDO;
import org.example.taobao.demo.good.repository.entity.GoodJpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * @author zhangxx
 * @date 2022/6/9 8:27 PM
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class GoodService {
    private final GoodJpaRepository goodJpaRepository;

    private final static String DEFAULT_PRICE_CURRENCY = "CNY";

    public String addGood(GoodDO goodDO) {
        Assert.hasText(goodDO.getGoodName(), "产品名称不能为空");
        Assert.notNull(goodDO.getPrice(), "产品价格不能为空");
        GoodDO saveResult = goodJpaRepository.save(goodDO);
        log.info("添加[{}]成功", goodDO.getGoodName());
        return saveResult.getGoodId();
    }

    public Optional<GoodDO> queryGood(String goodId) {
        return goodJpaRepository.findById(goodId);
    }


    /**
     * 扣减库存
     * todo 如果有多个节点，则该方法需要使用分布式锁
     * @param goodId 产品ID
     * @param numberOfStock 扣款库存数量
     * @return 成功或失败
     */
    public synchronized boolean deductStock(String goodId, Integer numberOfStock) {
        GoodDO goodDO = queryGood(goodId).orElseThrow(() -> new IllegalArgumentException("产品[" + goodId + "]不存在"));
        goodDO.deductStock(numberOfStock);
        goodJpaRepository.save(goodDO);
        log.info("deductStock [{}]-[{}], {}", goodId, goodDO.getGoodName(), numberOfStock);
        return true;
    }

}
